package com.acme.test;

import java.util.LinkedList;
import java.util.List;

import static org.junit.Assert.*;

import static org.hamcrest.core.Is.is;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.acme.StartServer;
import com.acme.domain.MarketData;
import com.acme.domain.Operationtype;
import com.acme.domain.Order;
import com.acme.domain.Responses;
import com.acme.domain.StartClient;
import com.acme.domain.Writer;
import com.acme.domain.request.PlaceOrderRequest;
import com.acme.domain.request.SubscribeMarketDataRequest;

public class SubscribeTestCase {
	
	private static List<Order> orderList = new LinkedList<Order>();
	private static int[] sortedIds = {2,1,3,7,6,5,4};
	
	@BeforeClass
	public static void setUpBeforeClass(){
		StartServer.start(2013);
		orderList.add(new Order("Oleg", Operationtype.BUY, "TNK", 10, 20f, 1));
		orderList.add(new Order("Oleg", Operationtype.BUY, "TNK", 10, 10f, 2));
		orderList.add(new Order("Oleg", Operationtype.BUY, "TNK", 10, 30f, 3));
		orderList.add(new Order("Oleg", Operationtype.SELL, "TNK", 10, 100f, 4));
		orderList.add(new Order("Oleg", Operationtype.SELL, "TNK", 10, 200f, 5));
		orderList.add(new Order("Oleg", Operationtype.SELL, "TNK", 10, 300f, 6));
		orderList.add(new Order("Oleg", Operationtype.SELL, "TNK", 10, 400f, 7));
		
	}
	
	@Before 
	public void setUp() throws Exception {
		StartClient.start("127.0.0.1", 2013, "Oleg");
	}

	@Test
	public void shouldRecieveCorrectMarketDataWhenSubscribed() throws InterruptedException {
		
		for (Order order : orderList) {
			Writer.writeRequest(new PlaceOrderRequest(order));
			Thread.sleep(50);
		}
		
		Writer.writeRequest(new SubscribeMarketDataRequest("TNK", "Oleg"));
		synchronized (MarketData.get()) {
			if (MarketData.get().isEmpty()){
				MarketData.get().wait();
			}
			for(int i=0; i<sortedIds.length;i++){
				assertThat(MarketData.get().get(i).getId(), is(sortedIds[i]));
			}
		}
		
	}
	
	@After
	public void tearDown() throws Exception{
		Responses.get().clear();
		StartClient.shutdown();
	}
	
	@AfterClass
	public static void tearDownAfterClass() throws Exception{
		StartServer.shutdown();
	}
}
